// 注册页面组件

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  TextField,
  Button,
  Typography,
  Alert,
  CircularProgress,
  IconButton,
  InputAdornment,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  Person,
  Email,
  Lock,
  Description,
  Send,
} from '@mui/icons-material';
import { useAuth } from '../../hooks';
import { RegisterRequest, RegisterAdminRequest, VerificationPurpose } from '../../types';
import styles from './Register.module.css';

type UserRole = 'USER' | 'ADMIN';

const Register: React.FC = () => {
  const navigate = useNavigate();
  const [userRole, setUserRole] = useState<UserRole>('USER');
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    verificationCode: '',
    bio: '',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [errors, setErrors] = useState<{[key: string]: string}>({});
  const [verificationSent, setVerificationSent] = useState(false);
  const [countdown, setCountdown] = useState(0);

  const { register, registerAdmin, sendVerificationCode, loading, error } = useAuth();

  // 倒计时效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: {[key: string]: string} = {};

    // 用户名验证
    if (!formData.username.trim()) {
      newErrors.username = '请输入用户名';
    } else if (formData.username.length < 3 || formData.username.length > 50) {
      newErrors.username = '用户名长度应在3-50字符之间';
    } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(formData.username)) {
      newErrors.username = '用户名只能包含字母、数字、下划线和中文';
    }

    // 邮箱验证
    if (!formData.email.trim()) {
      newErrors.email = '请输入邮箱地址';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    // 密码验证
    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 3 || formData.password.length > 20) {
      newErrors.password = '密码长度应在3-20字符之间';
    }

    // 确认密码验证
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = '请确认密码';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    // 验证码验证
    if (!formData.verificationCode.trim()) {
      newErrors.verificationCode = '请输入验证码';
    } else if (!/^\d{6}$/.test(formData.verificationCode)) {
      newErrors.verificationCode = '验证码应为6位数字';
    }

    // 个人简介验证（可选）
    if (formData.bio && formData.bio.length > 255) {
      newErrors.bio = '个人简介不能超过255字符';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理输入变化
  const handleInputChange = (field: string) => (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value
    }));
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: ''
      }));
    }
  };

  // 发送验证码
  const handleSendVerificationCode = async () => {
    if (!formData.email.trim()) {
      setErrors(prev => ({ ...prev, email: '请先输入邮箱地址' }));
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      setErrors(prev => ({ ...prev, email: '请输入有效的邮箱地址' }));
      return;
    }

    try {
      await sendVerificationCode({
        email: formData.email,
        purpose: VerificationPurpose.EMAIL_VERIFICATION
      });
      setVerificationSent(true);
      setCountdown(60);
    } catch (err) {
      console.error('发送验证码失败:', err);
    }
  };

  // 处理注册提交
  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    const requestData = {
      username: formData.username,
      email: formData.email,
      password: formData.password,
      verificationCode: formData.verificationCode,
      bio: formData.bio || undefined,
    };

    try {
      if (userRole === 'USER') {
        await register(requestData as RegisterRequest);
      } else {
        await registerAdmin(requestData as RegisterAdminRequest);
      }
      
      // 注册成功，跳转到登录页面
      console.log(`${userRole === 'USER' ? '用户' : '管理员'}注册成功`);
      navigate('/auth/login');
    } catch (err) {
      console.error('注册失败:', err);
    }
  };

  // 切换密码显示
  const handleTogglePasswordVisibility = () => {
    setShowPassword(prev => !prev);
  };

  const handleToggleConfirmPasswordVisibility = () => {
    setShowConfirmPassword(prev => !prev);
  };

  // 跳转到登录页面
  const handleGoToLogin = () => {
    navigate('/auth/login');
  };

  return (
    <Box className={styles.container}>
      <Card className={styles.registerCard}>
        <div className={styles.header}>
          <Typography variant="h4" className={styles.title}>
            创建账户
          </Typography>
          <Typography variant="body2" className={styles.subtitle}>
            加入小红书，开始分享您的精彩生活
          </Typography>
        </div>

        {/* 角色选择 */}
        <div className={styles.roleSelection}>
          <Typography variant="body2" className={styles.roleTitle}>
            选择账户类型
          </Typography>
          <div className={styles.roleOptions}>
            <div
              className={`${styles.roleOption} ${userRole === 'USER' ? styles.selected : ''}`}
              onClick={() => setUserRole('USER')}
            >
              <div className={styles.roleOptionTitle}>普通用户</div>
              <div className={styles.roleOptionDesc}>浏览和分享内容</div>
            </div>
            <div
              className={`${styles.roleOption} ${userRole === 'ADMIN' ? styles.selected : ''}`}
              onClick={() => setUserRole('ADMIN')}
            >
              <div className={styles.roleOptionTitle}>管理员</div>
              <div className={styles.roleOptionDesc}>管理平台内容</div>
            </div>
          </div>
          {userRole === 'ADMIN' && (
            <div className={styles.adminNotice}>
              注意：管理员账户需要超级管理员审核通过后才能正常使用
            </div>
          )}
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          <TextField
            fullWidth
            label="用户名"
            variant="outlined"
            value={formData.username}
            onChange={handleInputChange('username')}
            error={!!errors.username}
            helperText={errors.username}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Person color="action" />
                </InputAdornment>
              ),
            }}
          />

          <TextField
            fullWidth
            label="邮箱地址"
            type="email"
            variant="outlined"
            value={formData.email}
            onChange={handleInputChange('email')}
            error={!!errors.email}
            helperText={errors.email}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Email color="action" />
                </InputAdornment>
              ),
            }}
          />

          <div className={styles.verificationSection}>
            <TextField
              label="验证码"
              variant="outlined"
              value={formData.verificationCode}
              onChange={handleInputChange('verificationCode')}
              error={!!errors.verificationCode}
              helperText={errors.verificationCode}
              className={styles.verificationInput}
              placeholder="请输入6位数字验证码"
            />
            <Button
              variant="outlined"
              onClick={handleSendVerificationCode}
              disabled={countdown > 0 || loading}
              className={styles.verificationButton}
              startIcon={<Send />}
            >
              {countdown > 0 ? `${countdown}s` : verificationSent ? '重新发送' : '发送验证码'}
            </Button>
          </div>

          <TextField
            fullWidth
            label="密码"
            type={showPassword ? 'text' : 'password'}
            variant="outlined"
            value={formData.password}
            onChange={handleInputChange('password')}
            error={!!errors.password}
            helperText={errors.password}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Lock color="action" />
                </InputAdornment>
              ),
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={handleTogglePasswordVisibility}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />

          <TextField
            fullWidth
            label="确认密码"
            type={showConfirmPassword ? 'text' : 'password'}
            variant="outlined"
            value={formData.confirmPassword}
            onChange={handleInputChange('confirmPassword')}
            error={!!errors.confirmPassword}
            helperText={errors.confirmPassword}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Lock color="action" />
                </InputAdornment>
              ),
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={handleToggleConfirmPasswordVisibility}
                    edge="end"
                  >
                    {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />

          <TextField
            fullWidth
            label="个人简介（可选）"
            variant="outlined"
            multiline
            rows={3}
            value={formData.bio}
            onChange={handleInputChange('bio')}
            error={!!errors.bio}
            helperText={errors.bio || '最多255字符'}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Description color="action" />
                </InputAdornment>
              ),
            }}
          />

          <div className={styles.loadingWrapper}>
            <Button
              type="submit"
              fullWidth
              variant="contained"
              className={styles.registerButton}
              disabled={loading}
            >
              {loading ? '注册中...' : `注册${userRole === 'USER' ? '用户' : '管理员'}账户`}
            </Button>
            {loading && (
              <CircularProgress size={24} className={styles.loading} />
            )}
          </div>

          {error && (
            <Alert severity="error" className={styles.errorMessage}>
              {error}
            </Alert>
          )}

          {verificationSent && !error && (
            <Alert severity="success" className={styles.successMessage}>
              验证码已发送至您的邮箱，请查收
            </Alert>
          )}
        </form>

        <div className={styles.divider}>
          <span className={styles.dividerText}>或者</span>
        </div>

        <div className={styles.loginSection}>
          <Typography variant="body2" className={styles.loginText}>
            已有账户？
          </Typography>
          <Button
            variant="outlined"
            fullWidth
            onClick={handleGoToLogin}
            className={styles.loginButton}
          >
            立即登录
          </Button>
        </div>
      </Card>
    </Box>
  );
};

export default Register; 